package main

import (
	"fmt"
	"math"
)

//#link: https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/
func main() {
	nums := []int{2, 6, 4, 8, 10, 9, 15}
	//nums=[]int{1,2,3,4}
	fmt.Println(findUnsortedSubarray(nums))
}

func findUnsortedSubarray(nums []int) int {
	n := len(nums)
	minn, maxn := math.MaxInt64, math.MinInt64
	left, right := -1, -1
	for i, num := range nums {
		if maxn > num {
			right = i
		} else {
			maxn = num
		}
		if minn < nums[n-i-1] {
			left = n - i - 1
		} else {
			minn = nums[n-i-1]
		}
	}
	if right == -1 {
		return 0
	}
	return right - left + 1
}
